package puertocom;


import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Marcelo
 */
public class Receptor extends Thread {
    private static InputStream in;  
    private ImplProtocolo protocol = new ImplProtocolo();  
    public static boolean continuarLectura = true;
    
    static void closeInputStream()
    {
        if (in != null)
        {
            continuarLectura = false;
            try {
                in.close();
            } catch (IOException ex) {
                Logger.getLogger(Receptor.class.getName()).log(Level.SEVERE, null, ex);
            }
            in = null;
        }
    }
    
    public Receptor(InputStream in) {  
        this.in = in;  
    }  
    
    @Override
    public void run() {  
        try {  
            int b;  
            byte buf[] = new byte[1024];
            while(continuarLectura) {  
                int n=0;
                in.read(buf);
                while( in != null && (n=in.read(buf)) != -1) {  
                    protocol.seRecibio( buf, n );  
                }                  
                
                // si el flujo no ha receptado datos, devuelve -1
                /*while( in != null && (b = in.read()) != -1) {  
                    protocol.seRecibio( b);  
                } */ 
                protocol.seCerroStream();//para manejar los datos recibidos.
                  
                // Espear 10ms cuando el flujo se ha roto, para revisarlo neuvamente
                Thread.sleep(10);
            }  
            if (in != null)
                in.close();
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }   
    }      
}
